def notifyText(String wechatHook, String title, String message) {
    try {
        String content = """{
    "msg_type": "post",
    "content": {
        "post": {
            "zh_cn": {
                "title": "${title}",
                "content": [[
                    { "tag": "text", "text": "${message}" }
                ]]
            }
        }
    }
}"""
        httpRequest contentType: 'APPLICATION_JSON_UTF8', httpMode: 'POST', requestBody: content, url: wechatHook
    } catch (err) {
        echo err.getMessage()
    }
}

def notifyTest(String wechatHook, String app, String message) {
    try {
        String content = """{
    "msg_type": "post",
    "content": {
        "post": {
            "zh_cn": {
                "title": "测试消息",
                "content": [[
                    { "tag": "text", "text": "APP ${app} ${message}" }
                ]]
            }
        }
    }
}"""
        httpRequest contentType: 'APPLICATION_JSON_UTF8', httpMode: 'POST', requestBody: content, url: wechatHook
    } catch (err) {
        echo err.getMessage()
    }
}

def notifyApp(String repo, String branch, String eenv,String builder) {
    echo "repo:$repo,branch:$branch,env:$env,builder:$builder"

    // if (eenv == "EVOFLOW-DEV"){
    //     hanenv = "测试"
    // }

    // String hanenv = "预发"
    // if (eenv == "EVOFLOW-PROD"){
    //     hanenv = "生产"
    // }

    // if (eenv == "EVOFLOW-DEV"){
    //     hanenv = "测试"
    // }
    // if (!canBranchNotify(repo, branch, isSuccess)) {
    //     return
    // }




    try {
        buildjson = readJSON(text: "{}")
        String text = "### 项目：**${JOB_NAME}**\n > - 构建结果：**${currentBuild.result}**\n > - 构建环境：**${eenv}**\n > - 代码分支：**${branch}**\n > - 构建发起：**${builder}**\n  > - 构建日志：[点击查看详情](${env.BUILD_URL}console)"

        buildjson.text = text
        buildjson.username = "Jenkins助手"

        writeJSON(file: ".ci-notice.json", json: buildjson)

        sh "cat .ci-notice.json"
        def response = sh(script: "curl https://mind.im30.net/api/hooks/7mq6q6wdu7bkdp9mmwfqxinznw \
        -XPOST -H \"content-type: application/json\" \
        -d @.ci-notice.json",
                returnStdout: true)

        def json = readJSON(text: response)
        if (json.code == 0) {
            echo "成功完成发送通知... response: ${response}"
        }else{
            echo "通知失败：${response}"
            currentBuild.result = 'FAILURE'
        }

        // echo "通知成功"
    // String text = """
    // ### ${hanenv}环境发布${result} 
    // > - 项目名称：**${JOB_NAME}** 
    // > - 构建结果：**${result}** 
    // > - 构建环境：**${hanenv}** 
    // > - 代码分支：**${branch}** 
    // > - 构建发起：**${builder}**  
    // > - 构建日志：[点击查看详情](${env.BUILD_URL}console)"""
    // String content = 
    // """{
    //     "text": "${text}",
    //     "username":"Jenkins助手"
    // }"""
    // // String webhook = 'http://10.2.221.85:8082/jenkins/callback'
    // String webhook = 'https://mind.im30.net/api/hooks/wrddkh1iojye3ks653m78ecjio'
    // echo "content:${content}"
    // def response = httpRequest acceptType: 'APPLICATION_JSON_UTF8', contentType: 'APPLICATION_JSON_UTF8', httpMode: 'POST', requestBody: content, url: webhook
    // println("Status: ${response.status}")
    // println("Response: ${response.content}")
    // println("Headers: ${response.headers}")

    } catch (err) {
        echo err.getMessage()
    }
}


def graynotifyApp(String repo, String branch, String eenv, String builder) {
    echo "repo:$repo,branch:$branch,env:$env,builder:$builder"

    if (eenv == "EVOFLOW-PRE" || eenv == "EVOFLOW-DEV"){
        return
    }



    try {
        buildjson = readJSON(text: "{}")
        String text = "### 灰度环境构建${currentBuild.result}｜测试完成后请确认结果\n > - 项目名称：**${JOB_NAME}**\n > - 构建结果：**${currentBuild.result}**\n > - 构建环境：**${eenv}**\n > - 代码分支：**${branch}**\n > - 构建发起：**${builder}**\n  > - 构建日志：[点击查看详情](${env.BUILD_URL}console)"

        buildjson.text = text
        buildjson.username = "Jenkins助手"

        writeJSON(file: ".ci-notice.json", json: buildjson)

        sh "cat .ci-notice.json"
        def response = sh(script: "curl https://mind.im30.net/api/hooks/ggwq89q7hfdrx8iiq4gzxuyubo \
        -XPOST -H \"content-type: application/json\" \
        -d @.ci-notice.json",
                returnStdout: true)

        def json = readJSON(text: response)
        if (json.code == 0) {
            echo "成功完成发送通知... response: ${response}"
        }else{
            echo "通知失败：${response}"
            currentBuild.result = 'FAILURE'
        }
    } catch (err) {
        echo err.getMessage()
    }
}

def notifyRepo(Object config, String repo, String branch, boolean isSuccess) {
    if (config == null || config.wechatHook == null) {
        return
    }

    if (!canBranchNotify(config.repo, branch, isSuccess)) {
        return
    }

    String wechatHook = config?.wechatHook
    String result = "Repo 构建成功"
    message = sh(script: "git log -1 HEAD --pretty=format:%s", returnStdout: true).trim()
    author  = sh(script: "git log -1 HEAD --pretty=format:%cn", returnStdout: true).trim()
    buildMsg = "${currentBuild.displayName}"
    if (!isSuccess) {
        result = "Repo 构建失败"
    }
    try {
        String content = """{
    "msg_type": "post",
    "content": {
        "post": {
            "zh_cn": {
                "title": "${result}",
                "content": [[
                    { "tag": "text", "text": "项目 ${repo} 分支 ${branch} ${result}\\n" },
                    { "tag": "text", "text": "提交信息：${author} ${message}\\n" },
                    { "tag": "text", "text": "构建信息：" },
                    { "tag": "a", "text": "${buildMsg}", "href": "${env.BUILD_URL}" }
                ]]
            }
        }
    }
}"""
        httpRequest contentType: 'APPLICATION_JSON_UTF8', httpMode: 'POST', requestBody: content, url: wechatHook
    } catch (err) {
        echo err.getMessage()
    }
}

def notifyNpm(Object config, String repo, String branch, boolean isSuccess) {
    if (config == null || config.wechatHook == null) {
        return
    }

    if (!canBranchNotify(config.repo, branch, isSuccess)) {
        return
    }

    String wechatHook = config?.wechatHook
    String result = "NPM更新成功"
    tagStr = sh(script: "git log -1 | awk '{if(NR==5) print}'", returnStdout: true).trim()

    if (!tagStr.contains("_____im30fe_npm_update______")) {
        return
    }
    npmName = sh(script: "git log -1 | awk '{if(NR==6) print}'", returnStdout: true).trim()
        
    author  = sh(script: "git log -1 HEAD --pretty=format:%cn", returnStdout: true).trim()

    if (npmName) {
        versionStr = sh(script: "git log -1 | awk '{if(NR==7) print}'", returnStdout: true).trim()
        message = sh(script: "git log -1 | awk '{if(NR>7) print}'", returnStdout: true).trim()
    } else {
        infoArr = tagStr.split(" ")
        echo "${infoArr}"
        npmName = infoArr[1]
        versionStr = infoArr[2]
        infoArr = tagStr.split(" ${versionStr} ")
        message = infoArr[1]
    }

    String content = """{
    "msg_type": "post",
    "content": {
        "post": {
            "zh_cn": {
                "title": "${result}",
                "content": [[
                    { "tag": "text", "text": "${result} ${repo}\\n" },
                    { "tag": "text", "text": "包名：${npmName} \\n开发者：${author} \\n" },
                    { "tag": "text", "text": "版本：${versionStr} \\n${message.replaceAll('\n', '\\n')} \\n" },
                    { "tag": "a", "text": "构建链接", "href": "${env.BUILD_URL}" }
                ]]
            }
        }
    }
}"""

    if (!isSuccess) {
        return
        result = "NPM更新失败"
        content = """{
    "msg_type": "post",
    "content": {
        "post": {
            "zh_cn": {
                "title": "${result}",
                "content": [[
                    { "tag": "text", "text": "${result} ${repo}\\n" },
                    { "tag": "text", "text": "包名：${npmName} \\n开发者：${author} \\n" },
                    { "tag": "a", "text": "构建链接", "href": "${env.BUILD_URL}" }
                ]]
            }
        }
    }
}"""
    }
    try {
        echo content
        httpRequest contentType: 'APPLICATION_JSON_UTF8', httpMode: 'POST', requestBody: content, url: wechatHook
    } catch (err) {
        echo err.getMessage()
    }
}


def notifyDiff(Object config, String repo, String diff, String title, boolean isSuccess) {
    if (config == null || config.wechatHook == null) {
        return
    }

    if (!canNotify(config.diff, isSuccess)) {
        return
    }

    String wechatHook = config?.wechatHook
    String result = "Diff 构建成功"
    if (!isSuccess) {
        result = "Diff 构建失败"
    }
    String text = title
    if (text == null || text.size() <= 0) {
        text = "D${diff}"
    }
    try {
        String content = """{
    "msg_type": "post",
    "content": {
        "post": {
            "zh_cn": {
                "title": "${result}",
                "content": [[
                    { "tag": "text", "text": "项目 ${repo} Diff " },
                    { "tag": "a", "text": "${text}", "href": "https://phab.gotoim30.com/D${diff}" },
                    { "tag": "text", "text": "${result} \\n" },
                    { "tag": "a", "text": "构建链接", "href": "${env.BUILD_URL}" }
                ]]
            }
        }
    }
}"""
        httpRequest contentType: 'APPLICATION_JSON_UTF8', httpMode: 'POST', requestBody: content, url: wechatHook
    } catch (err) {
        echo err.getMessage()
    }
}

def notifyNodeDiff(Object config, String repo, String diff, String title, boolean isSuccess) {
    if (config == null || config.wechatHook == null) {
        return
    }

    if (!canNotify(config.diff, isSuccess)) {
        return
    }

    String wechatHook = config?.wechatHook
    String result = "Diff 构建成功"
    if (!isSuccess) {
        result = "Diff 构建失败"
    } else {
        return
    }
    String text = title
    if (text == null || text.size() <= 0) {
        text = "D${diff}"
    }
    try {
        String content = """{
    "msg_type": "post",
    "content": {
        "post": {
            "zh_cn": {
                "title": "${result}",
                "content": [[
                    { "tag": "text", "text": "项目 ${repo} Diff " },
                    { "tag": "a", "text": "${text}", "href": "https://phab.gotoim30.com/D${diff}" },
                    { "tag": "text", "text": "${result} \\n" },
                    { "tag": "a", "text": "构建链接", "href": "${env.BUILD_URL}" }
                ]]
            }
        }
    }
}"""
        httpRequest contentType: 'APPLICATION_JSON_UTF8', httpMode: 'POST', requestBody: content, url: wechatHook
    } catch (err) {
        echo err.getMessage()
    }
}

def canBranchNotify(Object option, String branch, boolean isSuccess) {

    if (option == null || option instanceof String) {
        return canNotify(option, isSuccess)
    }
    String opt = option[branch]
    return canNotify(opt, isSuccess)
}

def canNotify(String option, boolean isSuccess) {
    if (option == null || option.size() <= 0) {
        option = "OnFailure"
    }

    if ("None".equals(option)) {
        return false
    }

    if ("Always".equals(option)) {
        return true
    }

    return isSuccess
}